import { addUserApi, delUserApi, editUserApi } from '@/api/system/user/user'
import { AddUserModel, UserModel } from '@/api/system/user/UserModel'
import useInstance from '@/hooks/useInstance'
import { Result, StatusCode } from '@/http/request'
import { EditType } from '@/types/BaseEnum'
import { reactive, ref } from 'vue'

export default function useUser(getUserList: any) {
    const { global } = useInstance()

    // 新增弹框ref属性
    const addEditRef = ref<{
        show: (type: string, row?: UserModel) => void
    }>()

    // 分配角色弹框ref属性
    const assignRoleRef = ref<{
        show: (name: string, userId: string | number) => void
    }>()

    const addModel = reactive<UserModel>({
        type: '', //判断新增还是编辑
        id: '',
        username: '',
        password: '',
        nickname: '',
        status: '1',
        mobile: '',
        email: ''
    })

    // 新增
    const addBtn = () => {
        addModel.status = '1'
        // 显示弹框
        addEditRef.value?.show(EditType.ADD, addModel)
    }
    // 编辑
    const editBtn = (row: UserModel) => {
        row.status = String(row.status)
        // 显示弹框
        addEditRef.value?.show(EditType.EDIT, row)
    }
    // 删除
    const delBtn = async (id: number) => {
        const confirm = await global.$eleConfirm('确定删除该数据吗？')
        if (confirm) {
            // 执行删除操作
            let param = { id: id }
            let res = await delUserApi(param)
            if (res && res.code == StatusCode.Success) {
                // 刷新列表
                getUserList()
                // 信息提示
                global.$message({ message: res.msg, type: 'success' })
            }
        }
    }
    // 分配角色
    const assignBtn = (name: string, userId: string | number) => {
        // 显示弹框
        assignRoleRef.value?.show(name, userId)
    }

    // 保存
    const save = async (param: UserModel) => {
        const userParam = reactive<AddUserModel>({
            id: param.id,
            username: param.username,
            password: param.password,
            nickname: param.nickname,
            status: parseInt(param.status),
            mobile: param.mobile,
            email: param.email,
            avatar: ''
        })

        let res: Result
        if (param.type == EditType.ADD) {
            res = await addUserApi(userParam)
        } else {
            res = await editUserApi(userParam)
        }
        if (res && res.code == StatusCode.Success) {
            // 刷新列表
            getUserList()
            // 信息提示
            global.$message({ message: res.msg, type: 'success' })
        } else {
            global.$message({ message: res.msg, type: 'error' })
        }
    }
    return {
        addBtn,
        editBtn,
        delBtn,
        assignBtn,
        addEditRef,
        save,
        assignRoleRef
    }
}
